<template>
  <transition
    name="fade"
    @after-enter="afterEnter"
    @after-leave="afterLeave">
    <div class="baiwan-dialog-wrapper" v-show="visible" @click.self="handleWrapperClick">
      <div class="baiwan-dialog" ref="dialog" :style="style">
        <div class="baiwan-dialog-header">
          <slot name="title">
            <span class="baiwan-dialog-title">{{title}}</span>
          </slot>
          <span class="baiwan-dialog-close" @click="handleClose"><i class="iconfont">&#xe68c;</i></span>
        </div>
        <div class="baiwan-dialog-body">
          <slot></slot>
        </div>
        <div class="baiwan-dialog-footer">
          <slot name="footer"></slot>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
  export default {
    name: 'baiwan-dialog',
    data() {
      return {
        closed: false
      }
    },
    props: ['visible', 'title', 'beforeClose'],
    computed: {
      style() {
        let style = {}
        if (!this.fullscreen) {
          style.marginTop = this.top
          if (this.width) {
            style.width = this.width
          }
        }
        return style
      }
    },
    watch: {
      visible(val) {
        if (val) {
          this.closed = false
          this.$emit('open')
          this.$el.addEventListener('scroll', this.updatePopper)
          this.$nextTick(() => {
            this.$refs.dialog.scrollTop = 0
          })
          if (this.appendToBody) {
            document.body.appendChild(this.$el)
          }
        } else {
          this.$el.removeEventListener('scroll', this.updatePopper)
          if (!this.closed) this.$emit('close')
        }
      }
    },
    methods: {
      handleWrapperClick() {
        // if (!this.closeOnClickModal) return
        // this.handleClose()
      },
      handleClose() {
        if (typeof this.beforeClose === 'function') {
          this.beforeClose(this.hide)
        } else {
          this.hide()
        }
      },
      hide() {
        this.$emit('update:visible', false)
        this.$emit('close')
        this.closed = true
      },
      afterEnter() {
        this.$emit('opened')
      },
      afterLeave() {
        this.$emit('closed')
      }
    }
  }
</script>

<style scoped>
  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }

  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */
  {
    opacity: 0;
  }
</style>
